package com.csp.mingyue.common.doc.config;

import com.csp.mingyue.common.doc.support.SwaggerProperties;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.servers.Server;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.SpringDocConfiguration;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.context.annotation.Bean;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Swagger 配置
 *
 * @author Strive
 */
@RequiredArgsConstructor
@AutoConfiguration(before = SpringDocConfiguration.class)
@ConditionalOnProperty(name = "swagger.enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(SwaggerProperties.class)
@ConditionalOnMissingClass("org.springframework.cloud.gateway.config.GatewayAutoConfiguration")
public class SwaggerAutoConfiguration {

	private final SwaggerProperties swaggerProperties;

	private final ServiceInstance serviceInstance;

	@Bean
	public OpenAPI springOpenAPI() {
		OpenAPI openApi = new OpenAPI();
		// 文档基本信息
		SwaggerProperties.InfoProperties infoProperties = swaggerProperties.getInfo();
		Info info = convertInfo(infoProperties);
		openApi.info(info);

		// 鉴权方式配置
		openApi.components(swaggerProperties.getComponents());
		Set<String> keySet = swaggerProperties.getComponents().getSecuritySchemes().keySet();
		List<SecurityRequirement> list = new ArrayList<>();
		SecurityRequirement securityRequirement = new SecurityRequirement();
		keySet.forEach(securityRequirement::addList);
		list.add(securityRequirement);
		openApi.setSecurity(list);

		// servers 提供调用的接口地址前缀
		List<Server> serverList = new ArrayList<>();
		String path = swaggerProperties.getServices().get(serviceInstance.getServiceId());
		serverList.add(new Server().url(swaggerProperties.getGateway() + "/" + path));
		openApi.servers(serverList);

		return openApi;
	}

	/**
	 * 装填文档的基础属性信息
	 * @param infoProperties
	 * @return io.swagger.v3.oas.models.info.Info
	 */
	private Info convertInfo(SwaggerProperties.InfoProperties infoProperties) {
		Info info = new Info();
		info.setTitle(infoProperties.getTitle());
		info.setDescription(infoProperties.getDescription());
		info.setContact(infoProperties.getContact());
		info.setLicense(infoProperties.getLicense());
		info.setVersion(infoProperties.getVersion());
		return info;
	}

}
